<template>
  <div class="wft-editor flex flex-col" :style="{ height: props.height }">
    <Toolbar class="default-border" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor
      class="flex-1 overflow-y-auto"
      v-model="editData"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated" />
  </div>
</template>
<script setup>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { uploadFile, downloadFile } from '@/assets/api/document'
import { ElMessage } from 'element-plus'

const props = defineProps({
  defaultConfig: {
    type: Object,
    default: () => {
      return {
        placeholder: '请输入内容',
        readOnly: false,
        // 模式defalut默认模式simple精简模式
        mode: 'default',
        maxLength: 256,
      }
    },
  },
  // 回显html
  valueHtml: {
    type: String,
    default: '',
  },
  // 上传文件目录 从项目中获取
  folderId: {
    type: String,
    default: '',
  },
  // 文件夹相对路径
  folderName: {
    type: String,
    default: '',
  },
  // 富文本高度
  height: {
    type: String,
    default: '360px',
  },
  // 文件类型
  folderType: {
    type: String,
    default: 'project',
  },
  excludeKeys: {
    type: Array,
    default: () => ['group-video', 'emotion'],
  },
})
const mode = ref(props.defaultConfig.mode)
const editorRef = shallowRef()
const editData = ref()
const toolbarConfig = reactive({
  // 排除菜单
  excludeKeys: props.excludeKeys,
})
// toolbarConfig.value.excludeKeys = props.excludeKeys
const emit = defineEmits(['fullScreenFlag'])
// 监听赋值
watch(
  () => props.valueHtml,
  (val) => {
    if (val) {
      editData.value = val
    }
  },
  { deep: true, immediate: true }
)

// 模拟 ajax 异步获取内容--编辑初始值赋值
onMounted(() => {
  setTimeout(() => {
    editData.value = props.valueHtml
  }, 0)
})

// 富文本配置
const editorConfig = ref({
  placeholder: props.defaultConfig.placeholder,
  readOnly: props.defaultConfig.readOnly,
  maxLength: props.defaultConfig.maxLength,
  MENU_CONF: {
    uploadImage: {
      async customUpload(file, insertFn) {
        // file 即选中的文件
        // 自己实现上传，并得到图片 url alt href
        const form = new FormData()
        form.append('image', file)
        const formData = new FormData()
        formData.append('files', file)
        formData.append('folderParentId', props.folderId)
        formData.append('relativePath', props.folderName)
        formData.append('type', props.folderType)
        uploadFile(formData).then((res) => {
          if (res.code === 200) {
            const originalId = res.data[0].originalId
            const url =
              window.location.origin +
              process.env.VUE_APP_API_URL +
              `/chat-dx/resource/imageThumbnail/scale?originId=${originalId}&scale=1`
            insertFn(url, '', url)
          } else {
            ElMessage.error('上传失败')
          }
        })
      },
    },
  },
})
// 记录 editor 实例，重要！x
function handleCreated(editor) {
  editorRef.value = editor
  editorRef.value.fullScreen = () => {
    if (document.getElementsByClassName('w-e-full-screen-container').length > 0) {
      document.getElementsByClassName('wft-editor')[0].classList.remove('w-e-full-screen-container')
      // 取消全屏回调
      emit('fullScreenFlag', false)
    } else {
      document.getElementsByClassName('wft-editor')[0].classList.add('w-e-full-screen-container')
      // 全屏回调
      emit('fullScreenFlag', true)
    }
  }
}

// 销毁编辑器
onBeforeUnmount(() => {
  if (!editorRef.value) return
  editorRef.value.destroy()
})

function getHtml() {
  return editorRef.value.getHtml()
}
function getText() {
  return editorRef.value.getText()
}
defineExpose({ getHtml, getText })
</script>
<style lang="scss" scoped>
@import '@wangeditor/editor/dist/css/style.css';
.wft-editor {
  width: 100%;
  border: 1px solid #ccc;
  border-radius: 12px;
  overflow: hidden;
  z-index: 10;
}
.flex {
  display: flex;
}
.flex-col {
  flex-direction: column;
}
.default-border {
  border-bottom: 1px solid #ccc;
}
.flex-1 {
  flex: 1;
}
.overflow-y-auto {
  overflow-x: hidden;
  overflow-y: auto;
}
</style>
